<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request,
    App\Http\Controllers\Controller;

class LoginController extends Controller
{
    /**
     * login
     */
    public function index()
    {
        return [
            'code'     =>  -100,
            'msg'       =>  '你还没有登陆',
            'result'    =>  new \StdClass()
        ];
    }

    public function login(Request $request)
    {
        $phone = $request->input('phone');
        $password = $request->input('password');
        
        // 查询
        $user = \App\Model\User::where('phone',$phone)
            ->first([
                'id',
                'phone',
                'nick_name',
                'password',
                'avatar_url',
                'gender',
                'city',
                'province',
                'balance'
            ]);
        $user || returnJson('你还没有注册',-10);
        
        // 检测用密码
        $user->password != md5($password) && returnJson('密码错误',-10);

        $data = jwt_encode();
        // 更新数据库 token
        $user->token = $data['token'];
        $user->save();
        
        unset($user->password);
        $data['user'] = $user;
    
        // session(['user_info' => $user]);
        returnJson('登陆成功',0,$data);
    }

    public function token(Request $request){
        $token = $request->header('token');
        $token || $token = $request->token;

        if($token){
            
            // 查询用户修改token
            // 查询
            $user = \App\Model\User::where('token',$token)
                ->first([
                    'id',
                    'phone',
                    'nick_name',
                    'password',
                    'avatar_url',
                    'gender',
                    'city',
                    'province',
                    'balance'
                ]);
            $user || returnJson('token已经失效',-10);
        
            $data= jwt_builder($request->token);
            // 更新数据库 token
            $user->token = $data['token'];
            $user->save();

            $data['user'] = $user;
            returnJson('登陆成功',0,$data);

        }else{
            returnJson('缺少token',-500);
        }
    }


}
